package com.zzmcc.sys.controller;


import com.jfinal.ext.kit.PoiKit;
import com.jfinal.ext.render.excel.JxlsRender;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.zzmcc.base.BaseController;
import com.zzmcc.common.Constant;
import util.CastUtil;
import util.DegreesUtil;
import util.Levenshtein;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class DegreeController extends BaseController {
	public void index() {

		render("../degree.html");
	}
	public void down(){

		String templateFileName = PathKit.getRootClassPath() + "/tpl_degree.xls";

		renderFile(new File(templateFileName));
	}
	public void export(){

		String path = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
		UploadFile file = getFile();

		String fileName = null;

		if (file !=null) {
			File source = file.getFile();
			fileName = file.getFileName();

			try {
				FileInputStream fis = new FileInputStream(source);
				File targetDir = new File(Constant.UPLOAD_FILE_DIR  + path);

				if (!targetDir.exists()) {
					targetDir.mkdirs();
				}
				File target = new File(targetDir, fileName);
				if (!target.exists()) {
					target.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(target);
				byte[] bts = new byte[300];
				while (fis.read(bts, 0, 300) != -1) {
					fos.write(bts, 0, 300);
				}
				fos.close();
				fis.close();
				source.delete();
			} catch (FileNotFoundException e) {

				renderDWZErrorJson("上传出现错误，请稍后再上传");
			} catch (IOException e) {

				renderDWZErrorJson("文件写入服务器出现错误，请稍后再上传");
			}
		}
		String templateFileName = Constant.UPLOAD_FILE_DIR + path +"/" +fileName;
		List<Record> records  = new ArrayList<Record>();
		Object[][] dataArr =null;
		int flag =getParaToInt("flag");
		if(flag==1) {
			dataArr = PoiKit.ReadExcel(templateFileName, "转度分秒格式");
		}else {
			dataArr = PoiKit.ReadExcel(templateFileName, "转数值格式");
		}

		for(int i=1;i<dataArr.length;i++){

			Record record = new Record();
			String lon=CastUtil.castString(dataArr[i][1]);
			String lat=CastUtil.castString(dataArr[i][2]);
			String lon_value ,lat_value;
			if(flag==1) {
				lon_value= DegreesUtil.ConvertDigitalToDegrees(lon);
				lat_value= DegreesUtil.ConvertDigitalToDegrees(lat);
			}else {
				//匹配
				java.text.DecimalFormat   df=new   java.text.DecimalFormat("#.#####");
				lon_value= df.format(DegreesUtil.ConvertDegreesToDigital(lon));
				lat_value= df.format(DegreesUtil.ConvertDegreesToDigital(lat));
			}
			record.set("id", dataArr[i][0]);
			record.set("lon",lon_value);
			record.set("lat", lat_value);
			records.add(record);
		}

		Map<String, Object> beans = new HashMap<String, Object>();
		beans.put("records", records);
		String filename = "degree.xls";
		render(JxlsRender.me(templateFileName).filename(filename).beans(beans));

	}


}
